package com.tedu.weibo.common.exception;

import com.tedu.weibo.common.result.JsonResult;
import com.tedu.weibo.common.result.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException e) {
        log.error("捕获到异常：{}", e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e) {
        log.error("捕获到异常：{}",e.getMessage(), e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable throwable) {
        log.error("捕获到异常：{}", throwable.getMessage(), throwable);
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("捕获到异常：{}", Objects.requireNonNull(e.getFieldError()).getDefaultMessage(), e);
        return new JsonResult(StatusCode.VALIDATE_ERROR,Objects.requireNonNull(e.getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e) {
        log.error("捕获到异常：{}", e.getConstraintViolations().iterator().next().getMessage(),e);
        return new JsonResult(StatusCode.VALIDATE_ERROR,e.getConstraintViolations().iterator().next().getMessage());
    }
}
